package at.fhooe.mcm12.swa.ex3.db;

import java.util.Vector;

import at.fhooe.mcm12.swa.ex3.event.Event;
import at.fhooe.mcm12.swa.ex3.event.FinishEvent;
import at.fhooe.mcm12.swa.ex3.event.StartEvent;
import at.fhooe.mcm12.swa.ex3.event.StoryEvent;
import at.fhooe.mcm12.swa.ex3.model.Runner;

/**
 * The Class DBAbstractionLayer.
 */
public class DBAbstractionLayer {
	
	/** The server connection. */
	private DBConnection serverConnection;
	
	/** The runners. */
	private Vector<Runner> runners;

	/**
	 * Instantiates a new dB abstraction layer.
	 *
	 * @param _connection the _connection
	 */
	public DBAbstractionLayer(DBConnection _connection) {
		this.serverConnection = _connection;

		serverConnection.open();

		if (serverConnection.isConnected()) {
			this.runners = this.serverConnection.getData();
		}

		serverConnection.close();
	}

	/**
	 * Gets the runners.
	 *
	 * @return the runners
	 */
	public Vector<Runner> getRunners() {
		return this.runners;
	}

	/**
	 * Gets the all runners.
	 *
	 * @return the all runners
	 */
	public Vector<Runner> getAllRunners() {
		return this.runners;
	}

	/**
	 * Gets the number runners.
	 *
	 * @return the number runners
	 */
	public int getNumberRunners() {
		return this.runners.size();
	}

	/**
	 * Gets the mean story time.
	 *
	 * @return the mean story time
	 */
	public long getMeanStoryTime() {
		long mean = 0;

		for (Runner run : this.runners) {
			Vector<Event> events = run.getEvents();
			long startTime = 0;
			long lastTime = 0;
			int story = -1;
			for (Event event : events) {
				if (event instanceof StoryEvent) {
					if (((StoryEvent) event).getActStory() > story) {
						story = ((StoryEvent) event).getActStory();
						lastTime = event.getTimeStamp();
					}
				} else if (event instanceof StartEvent) {
					startTime = event.getTimeStamp();
				}
			}

			if ((startTime != 0) && (lastTime != 0)) {
				if (mean > 0) {
					mean = (mean + ((lastTime - startTime)/story)) / 2;
				} else {
					mean = (lastTime - startTime)/story;
				}
			}
		}

		return mean;
	}

	/**
	 * Gets the number finished.
	 *
	 * @return the number finished
	 */
	public int getNumberFinished() {
		int finished = 0;

		for (Runner run : this.runners) {
			Vector<Event> events = run.getEvents();
			for (Event event : events) {
				if (event instanceof FinishEvent) {
					finished++;
				}
			}
		}

		return finished;
	}

	/**
	 * Gets the number started.
	 *
	 * @return the number started
	 */
	public int getNumberStarted() {
		int started = 0;

		for (Runner run : this.runners) {
			Vector<Event> events = run.getEvents();
			for (Event event : events) {
				if (event instanceof StartEvent) {
					started++;
				}
			}
		}

		return started;
	}

}
